package com.zyht.website.controller;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.zyht.common.AbsPrintBaseController;
import com.zyht.common.util.FileUploadUtil;

@Controller
@RequestMapping("anon/material")
public class CommonUploaderController extends AbsPrintBaseController{

	@RequestMapping(value="image", method=RequestMethod.GET)
	public String openUploadImageWin(@RequestParam("t") Integer useThumb, Integer w, Integer h, String n, Model model){
		model.addAttribute("useThumb",useThumb);
		model.addAttribute("w",w);
		model.addAttribute("h",h);
		model.addAttribute("n",n);
		return "/frame/modules/uploader/image_uploader";
	}
	
	@RequestMapping(value="image", method=RequestMethod.POST)
	public void doUploadImage(MultipartFile picture, Integer useThumb, Integer w, Integer h, String n, HttpServletResponse response, HttpServletRequest request){
		String oName = picture.getOriginalFilename();
		String parentFolder = request.getSession().getServletContext().getRealPath("/upload");
		String prePath = "/image/".concat(n).concat("/");
		parentFolder = parentFolder.concat(prePath);
		try{
			InputStream is = picture.getInputStream();
			if(null==is){
				throw new IOException("文件流为空！");
			}
			String fileName =  null;
			if(0!=useThumb){
				fileName = FileUploadUtil.doUploadImageWithThumb(parentFolder,is,oName,w,h);
			}else{
				fileName = FileUploadUtil.doUpload(parentFolder, is, oName);
			}
			if(null!=fileName){
				writeHtml(response, "<script type='text/javascript'>window.parent.closeWin('/upload"+prePath.concat(fileName)+"')</script>");
			}else{
				writeHtml(response, "<script type='text/javascript'>window.parent.closeWin(null)</script>");
			}
		} catch (IOException e){
			e.printStackTrace();
			writeHtml(response, "<script type='text/javascript'>window.parent.closeWin(null)</script>");
		}
	}
	
	@RequestMapping(value="video", method=RequestMethod.GET)
	public String openUploadVideoWin(){
		return "/frame/modules/uploader/video_uploader";
	}
	
	@RequestMapping(value="video", method=RequestMethod.POST)
	public void doUploadVideo(MultipartFile video, HttpServletResponse response, HttpServletRequest request){
		
	}
	
	@RequestMapping(value="file", method=RequestMethod.GET)
	public String openUploadFileWin(){
		return "/frame/modules/uploader/file_uploader";
	}
	
	@RequestMapping(value="file", method=RequestMethod.POST)
	public void doUploadFile(MultipartFile file, HttpServletResponse response, HttpServletRequest request){
		
	}
}
